using System;
using System.Collections.Generic;
using Main.Item;

namespace ZSW.Framework
{
    /// <summary>
    /// 容器，对于各个模块功能进行统一管理
    /// </summary>
    public class ZSWF_IOCContainer
    {
        private static Dictionary<Type, object> m_instances = new Dictionary<Type, object>();

        public static int Count => m_instances.Count;
        public static void Register<T>(T instance)
        {
            var key = typeof(T);

            if (m_instances.ContainsKey(key))
            {
                m_instances[key] = instance;
            }
            else
            {
                m_instances.Add(key, instance);
            }

            if (m_instances is IInit)
            {
                ((IInit)m_instances).Init();
            }
        }

        public static T Get<T>() where T : class
        {
            var key = typeof(T);

            if (m_instances.TryGetValue(key, out var retInstance))
            {
                return retInstance as T;
            }

            return null;
        }

        public static string PrintAllInstances()
        {
            var sb = new System.Text.StringBuilder();
            foreach (Type item in m_instances.Keys)
            {
                sb.AppendLine(item.Name.ToString());
            }

            return sb.ToString();
        }
    }
}
